using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using Voodoo.Sauce.Internal.CrossPromo.Mobile;
using Voodoo.Sauce.Internal.CrossPromo.Models;
using Voodoo.Sauce.Internal.CrossPromo.Utils;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	public class VideoManager
	{
		private readonly RenderTexture _renderTexture;

		public RawImage Content
		{
			get;
			private set;
		}

		public VideoPlayer VideoPlayer
		{
			get;
			private set;
		}

		public VideoManager(VideoPlayer video, RawImage content)
		{
			VideoPlayer = video;
			Content = content;
			Content.enabled = false;
			VideoPlayer.prepareCompleted += OnVideoComplete;
			_renderTexture = new RenderTexture(0, 0, 24);
		}

		public AssetModel ChooseVideo()
		{
			CrossPromoInfo info = VoodooCrossPromo.Info;
			if (info.Assets.Count <= info.Waterfall.Count)
			{
				info.Waterfall.Clear();
			}
			List<AssetModel> list = new List<AssetModel>(info.Assets);
			foreach (AssetModel item in list)
			{
				if (CacheManager.IsFileExist(item.file_path) && !info.Waterfall.Contains(item))
				{
					if (!MobileCrossPromoWrapper.IsAppInstalled(item.game))
					{
						info.Waterfall.Add(item);
						return item;
					}
					info.Assets.Remove(item);
				}
			}
			info.Waterfall.Clear();
			if (info.Assets.Count == 0)
			{
				return null;
			}
			AssetModel assetModel = info.Assets[0];
			info.Waterfall.Add(assetModel);
			return assetModel;
		}

		public void PrepareVideo(AssetModel asset)
		{
			if (_renderTexture.IsCreated())
			{
				ReleaseTexture();
			}
			if (!CacheManager.IsFileExist(asset.file_path))
			{
				throw new Exception("Can not read the file because it doesn't exist");
			}
			VideoPlayer.url = CacheManager.Path + asset.file_path;
			VideoPlayer.Prepare();
		}

		public void StopVideo()
		{
			Content.enabled = false;
			VideoPlayer.Stop();
		}

		private void ReleaseTexture()
		{
			_renderTexture.Release();
			_renderTexture.DiscardContents();
		}

		private void OnVideoComplete(VideoPlayer source)
		{
			int width = source.texture.width;
			int height = source.texture.height;
			if (!_renderTexture.IsCreated())
			{
				_renderTexture.width = width;
				_renderTexture.height = height;
			}
			_renderTexture.Create();
			VideoPlayer.targetTexture = _renderTexture;
			Content.texture = _renderTexture;
			Content.enabled = true;
			ReleaseTexture();
		}
	}
}
